package com.engine.jz.util;

import com.huawei.shade.org.joda.time.DateTime;
import com.huawei.shade.org.joda.time.format.DateTimeFormat;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import weaver.file.ImageFileManager;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2024/11/26
 * @Description 公共类
 * @Author AdminZm
 */
public class CommonUtil {

    // AES加密/解密算法/模式/填充
    private static final String ALGORITHM = "AES/ECB/PKCS5Padding"; // 注意：Java标准库中只支持PKCS5Padding，但效果等同于PKCS7Padding

    public static String getString(HttpResponse response) throws IOException {
        String result = null;
        if (response != null) {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, "utf-8");
            }
        }
        return result;
    }

    public static String getDateStrFromIso8601(String dateStr){
        com.huawei.shade.org.joda.time.format.DateTimeFormatter dtf1 = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ");
        DateTime dt= dtf1.parseDateTime(dateStr);
        com.huawei.shade.org.joda.time.format.DateTimeFormatter dtf2= DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        return dt.toString(dtf2);
    }

    // AES加密
    public static String encrypt(String plainText, String key) throws Exception {
        // 将字符串秘钥转换为AES密钥
        byte[] keyBytes = key.getBytes("UTF-8");
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

        // 创建AES加密器，并指定加密模式和填充方式
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        // 执行加密操作
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));

        // 将加密后的数据进行Base64编码
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String imageBase64(int imageId) throws IOException {
        String base64 = "";
        // 读取图片字节数组
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            //weaver.file.ImageFileManager#getInputStreamById 直接这个就能获取文件流
            in = ImageFileManager.getInputStreamById(imageId);
            out = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            byte[] imageBytes = out.toByteArray();
            base64 = Base64.getEncoder().encodeToString(imageBytes);
            return base64;
        } catch (Exception e) {
            return base64;
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }

    public static String removeLeadingZeros(String input) {
        // 找到第一个非0字符的索引
        int firstNonZeroIndex = -1;
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (ch != '0') {
                firstNonZeroIndex = i;
                break;
            }
        }

        // 如果firstNonZeroIndex为-1，说明字符串全为0，返回"0"或者空字符串，取决于你的需求
        // 这里假设返回空字符串
        if (firstNonZeroIndex == -1) {
            return "";
        }

        // 返回从第一个非0字符开始到字符串末尾的子字符串
        return input.substring(firstNonZeroIndex);
    }

    /**
     * 获取下一个编号，并转成指定位数
     * @param startValue  上一个编号
     * @param digit  位数
     */
    public static String getNext(Integer startValue, int digit) {
        AtomicInteger val = new AtomicInteger(startValue);
        int nextVal = val.incrementAndGet();
        String format = "%0" + digit + "d";
        return String.format(format, nextVal);
    }

}
